/*
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

*/
/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 *//*


packageName = "priv.jesse.mall.entity.pojo;"
typeMapping = [
  (~/(?i)int/)                      : "long",
  (~/(?i)float|double|decimal|real/): "double",
  (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
  (~/(?i)date/)                     : "java.sql.Date",
  (~/(?i)time/)                     : "java.sql.Time",
  (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
  SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
  def className = javaName(table.getName(), true)
  def fields = calcFields(table)
  new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields) }
}

def generate(out, className, fields) {
  out.println "package $packageName"
  out.println ""
  out.println ""
  out.println "public class $className {"
  out.println ""
  fields.each() {
    if (it.annos != "") out.println "  ${it.annos}"
    out.println "  private ${it.type} ${it.name};"
  }
  out.println ""
  fields.each() {
    out.println ""
    out.println "  public ${it.type} get${it.name.capitalize()}() {"
    out.println "    return ${it.name};"
    out.println "  }"
    out.println ""
    out.println "  public void set${it.name.capitalize()}(${it.type} ${it.name}) {"
    out.println "    this.${it.name} = ${it.name};"
    out.println "  }"
    out.println ""
  }
  out.println "}"
}

def calcFields(table) {
  DasUtil.getColumns(table).reduce([]) { fields, col ->
    def spec = Case.LOWER.apply(col.getDataType().getSpecification())
    def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
    fields += [[
                 name : javaName(col.getName(), false),
                 type : typeStr,
                 annos: ""]]
  }
}

def javaName(str, capitalize) {
  def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
    .collect { Case.LOWER.apply(it).capitalize() }
    .join("")
    .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
  capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
*/


import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

config = [
        impSerializable     : true,
        extendBaseEntity    : true,
        extendBaseService   : true,
        extendBaseRepository:true,
        useLombok           : false, // 不使用会生成get、set方法

        // 不生成哪个就注释哪个
        generateItem     : [
                "Entity",
                "Service",
                "ServiceImpl",
                "Dao",
//                "Repository",
//                "RepositoryCustom",
//                "RepositoryImpl",
        ]
]

baseEntityPackage = "com.zstu.mall.common.BaseEntity"
baseServicePackage = "com.zstu.mall.common.BaseService"
baseServiceImplPackage = "com.zstu.mall.common.BaseServiceImpl"
baseRepositoryPackage = "com.zstu.mall.common.BaseRepository"
baseEntityProperties = ["id", "gmtCreate", "gmtModified", "status", "remark"]
createDateTime = "2019/11/24"

typeMapping = [
        (~/(?i)bool|boolean|tinyint/)     : "Boolean",
        (~/(?i)bigint/)                   : "Long",
        (~/int/)                          : "Integer",
        (~/(?i)float|double|decimal|real/): "Double",
        (~/(?i)datetime|timestamp/)       : "java.util.Date",
        (~/(?i)date/)                     : "java.sql.Date",
        (~/(?i)time/)                     : "java.sql.Time",
        (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter {
        it instanceof DasTable && it.getKind() == ObjectKind.TABLE
    }.each {
        generate(it, dir)
    }
}

// 生成对应的文件
def generate(table, dir) {

    def entityPath = "${dir.toString()}\\entity",
        servicePath = "${dir.toString()}\\service",
        serviceImpPath = "${dir.toString()}\\service\\impl",
        daoPath = "${dir.toString()}\\dao",
//        repImpPath = "${dir.toString()}\\repository\\impl",
        controllerPath = "${dir.toString()}\\controller"

    mkdirs([entityPath, servicePath, serviceImpPath, daoPath,/* repPath, repImpPath,*/ controllerPath])

    System.out.println(table.getName())
    def entityName = javaName(table.getName(), true)
    def fields = calcFields(table)
    def basePackage = clacBasePackage(dir)

    if (isGenerate("Entity")) {
        genUTF8File(entityPath, "${entityName}.java").withPrintWriter { out -> genEntity(out, table, entityName, fields, basePackage) }
    }
    if (isGenerate("Service")) {
        genUTF8File(servicePath, "${entityName}Service.java").withPrintWriter { out -> genService(out, table, entityName, fields, basePackage) }
    }
    if (isGenerate("ServiceImpl")) {
        genUTF8File(serviceImpPath, "${entityName}ServiceImpl.java").withPrintWriter { out -> genServiceImpl(out, table, entityName, fields, basePackage) }
    }
    if (isGenerate("Dao")) {
        genUTF8File(daoPath, "${entityName}Dao.java").withPrintWriter { out -> genDao(out, table, entityName, fields, basePackage) }
    }
    /*if (isGenerate("Repository")) {
        genUTF8File(repPath, "${entityName}Repository.java").withPrintWriter { out -> genRepository(out, table, entityName, fields, basePackage) }
    }
    if (isGenerate("RepositoryCustom")) {
        genUTF8File(repPath, "${entityName}RepositoryCustom.java").withPrintWriter { out -> genRepositoryCustom(out, entityName, basePackage) }
    }
    if (isGenerate("RepositoryImpl")) {
        genUTF8File(repImpPath, "${entityName}RepositoryImpl.java").withPrintWriter { out -> genRepositoryImpl(out, table, entityName, fields, basePackage) }
    }*/

}

//生成注解
def genAnnotation(out, description){
    out.println "/**"
    out.println " * @author     : wuyc"
    out.println " * @description: $description"
    out.println " * @date       : Created in $createDateTime"
    out.println " */"
}

// 是否需要被生成
def isGenerate(itemName) {
    config.generateItem.contains(itemName)
}

// 指定文件编码方式，防止中文注释乱码
def genUTF8File(dir, fileName) {
    new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, fileName)), "utf-8"))
}

// 生成每个字段
def genProperty(out, field) {

    out.println ""
    out.println "\t/**"
    out.println "\t * ${field.comment}"
    out.println "\t * default value: ${field.default}"
    out.println "\t */"
    // 默认表的第一个字段为主键
    if (field.position == 1) {
        out.println "\t@Id"
        //主键生成策略
//        out.println "\t@GeneratedValue"
    }
    // 枚举enum不需要长度,时间datetime不给长度
    out.println "\t@Column(name = \"${field.colum}\", nullable = ${!field.isNotNull}${field.dataType == "enum" ? "" : ",length = $field.len"})"
    out.println "\tprivate ${field.type} ${field.name};"
}

// 生成get、get方法
def genGetSet(out, field) {

    // get
    out.println "\t"
    out.println "\tpublic ${field.type} get${field.name.substring(0, 1).toUpperCase()}${field.name.substring(1)}() {"
    out.println "\t\treturn this.${field.name};"
    out.println "\t}"

    // set
    out.println "\t"
    out.println "\tpublic void set${field.name.substring(0, 1).toUpperCase()}${field.name.substring(1)}(${field.type} ${field.name}) {"
    out.println "\t\tthis.${field.name} = ${field.name};"
    out.println "\t}"
}

// 生成实体类
def genEntity(out, table, entityName, fields, basePackage) {
    out.println "package ${basePackage}.entity;"
    out.println ""
    if (config.extendBaseEntity) {
        out.println "import $baseEntityPackage;"
    }
    if (config.useLombok) {
        out.println "import lombok.Data;"
        out.println ""
    }
    if (config.impSerializable) {
        out.println "import java.io.Serializable;"
        out.println ""
    }
    out.println "import java.util.Date;"
    out.println "import javax.persistence.*;"
    out.println ""
    genAnnotation(out, "${table.getName()}")
    if (config.useLombok) {
        out.println "@Data"
    }
    out.println "@Entity"
    //继承父类的属性的策略(TABLE_PER_CLASS为每个类创建一个表)
    out.println "@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)"
    out.println "@Table(name = \"${table.getName()}\")"
    out.println "public class $entityName${config.extendBaseEntity ? " extends BaseEntity" : ""}${config.impSerializable ? " implements Serializable" : ""} {"

    if (config.extendBaseEntity) {
        fields = fields.findAll { it ->
            !baseEntityProperties.any { it1 -> it1 == it.name }
        }
    }

    fields.each() {
        genProperty(out, it)
    }

    out.println ""
    out.println "\tpublic $entityName() {"
    out.println "\t\tsuper(); "
    out.println "\t\tsuper.status = \"1\"; "
    out.println "\t\tsuper.remark = \" \"; "
    out.println "\t\tsuper.gmtCreate = new Date(); "
    out.println "\t\tsuper.gmtModified = new Date(); "
    fields.each() {
        if("${it.type}" == "String"){
            out.print "\t\tthis.${it.name} = "
            String str = "${it.default}";
            out.print str.replace("\'","\"");
            out.println ";"
        }
        if("${it.type}" == "Double"){
            out.println "\t\tthis.${it.name} = ${it.default}.0;"
        }
    }
    out.println "\t}"

    if (!config.useLombok) {
        fields.each() {
            genGetSet(out, it)
        }
    }
    out.println "}"
}

// 生成Service
def genService(out, table, entityName, fields, basePackage) {
    out.println "package ${basePackage}.service;"
    out.println ""
    if (config.extendBaseService) {
        out.println "import $baseServicePackage;"
    }
    out.println "import ${basePackage}.entity.$entityName;"
    out.println "import ${basePackage}.dao.${entityName}Dao;"
    out.println ""
    genAnnotation(out, "${entityName}Service")
    out.println "public interface ${entityName}Service${config.extendBaseService ? " extends BaseService<$entityName, String, ${entityName}Dao>" : ""}  {"
    out.println ""
    out.println "}"
}

// 生成ServiceImpl
def genServiceImpl(out, table, entityName, fields, basePackage) {
    out.println "package ${basePackage}.service.impl;"
    out.println ""
//    out.println "import ${basePackage}.repository.${entityName}Repository;"
    out.println "import org.springframework.stereotype.Service;"
    out.println "import org.springframework.beans.factory.annotation.Autowired;"
    if (config.extendBaseService) {
        out.println "import $baseServiceImplPackage;"
//        out.println "import ${basePackage}.entity.$entityName;"
    }
    out.println "import ${basePackage}.service.${entityName}Service;"
    out.println "import ${basePackage}.entity.$entityName;"
    out.println "import ${basePackage}.dao.${entityName}Dao;"
    out.println ""
//    out.println "import javax.annotation.Resource;"
    genAnnotation(out, "${entityName}ServiceImpl")
    out.println "@Service"
    out.println "public class ${entityName}ServiceImpl extends BaseServiceImpl<$entityName, String, ${entityName}Dao> implements ${entityName}Service {"
    out.println ""
    out.println "\t@Autowired"
    out.println "\tprivate ${entityName}Dao ${table.getName()}dao;"
    out.println ""
//    out.println "\t@Resource"
//    out.println "\tprivate ${entityName}Repository rep;"
    out.println "}"
}

// 生成Dao
def genDao(out, table, entityName, fields, basePackage) {
    out.println "package ${basePackage}.dao;"
    out.println ""
    out.println "import $baseRepositoryPackage;"
    out.println "import ${basePackage}.entity.$entityName;"
    out.println ""
    genAnnotation(out, "${entityName}Dao")
    out.println "public interface ${entityName}Dao extends BaseRepository<$entityName, String> {"
    out.println ""
    out.println "}"
}

// 生成Repository
/*def genRepository(out, table, entityName, fields, basePackage) {
    out.println "package ${basePackage}.repository;"
    out.println ""
    out.println "import ${basePackage}.entity.$entityName;"
    out.println "import org.springframework.data.jpa.repository.JpaRepository;"
    out.println ""
    genAnnotation(out, "${entityName}Repository")
    out.println "public interface ${entityName}Repository extends JpaRepository<$entityName, ${fields[0].type}>, ${entityName}RepositoryCustom {"
    out.println ""
    out.println "}"
}*/

// 生成RepositoryCustom(自定义接口,实现公共之外的业务)
/*def genRepositoryCustom(out, entityName, basePackage) {
    out.println "package ${basePackage}.repository;"
    out.println ""
    genAnnotation(out, "${entityName}RepositoryCustom")
    out.println "public interface ${entityName}RepositoryCustom {"
    out.println ""
    out.println "}"
}*/

// 生成RepositoryImpl
/*def genRepositoryImpl(out, table, entityName, fields, basePackage) {
    out.println "package ${basePackage}.repository.impl;"
    out.println ""
    out.println "import ${basePackage}.repository.${entityName}RepositoryCustom;"
    out.println "import org.springframework.stereotype.Repository;"
    out.println ""
    out.println "import javax.persistence.EntityManager;"
    out.println "import javax.persistence.PersistenceContext;"
    out.println ""
    genAnnotation(out, "${entityName}RepositoryImpl")
    out.println "@Repository"
    out.println "public class ${entityName}RepositoryImpl implements ${entityName}RepositoryCustom {"
    out.println ""
    out.println "\t@PersistenceContext"
    out.println "\tprivate EntityManager em;"
    out.println "}"
}*/

// 生成文件夹
def mkdirs(dirs) {
    dirs.forEach {
        def f = new File(it)
        if (!f.exists()) {
            f.mkdirs()
        }
    }
}

def clacBasePackage(dir) {
    dir.toString()
            .replaceAll("^.+\\\\src\\\\main\\\\java\\\\", "")
            .replaceAll("\\\\", ".")
}

def isBaseEntityProperty(property) {
    baseEntityProperties.find { it == property } != null
}

// 转换类型
def calcFields(table) {
    DasUtil.getColumns(table).reduce([]) { fields, col ->

        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        fields += [[
                           name     : javaName(col.getName(), false),
                           colum    : col.getName(),
                           type     : typeStr,
                           dataType : col.getDataType().toString().replaceAll(/\(.*\)/, "").toLowerCase(),
                           len      : col.getDataType().toString().replaceAll(/[^\d]/, ""),
                           default  : col.getDefault(),
                           comment  : col.getComment(),
                           isNotNull: col.isNotNull(),
                           position : col.getPosition(),
//                           getDefault            : col.getDefault(),
//                           getParent             : col.getParent(),
//                           getTable              : col.getTable(),
//                           getDataType           : col.getDataType(),
//                           isNotNull             : col.isNotNull(),
//                           getWeight             : col.getWeight(),
//                           getDocumentation      : col.getDocumentation(),
//                           getTableName          : col.getTableName(),
//                           getName               : col.getName(),
//                           getLanguage           : col.getLanguage(),
//                           getTypeName           : col.getTypeName(),
//                           isDirectory           : col.isDirectory(),
//                           isValid               : col.isValid(),
//                           getComment            : col.getComment(),
//                           getText               : col.getText(),
//                           getDeclaration        : col.getDeclaration(),
//                           getPosition           : col.getPosition(),
//                           canNavigate           : col.canNavigate(),
//                           isWritable            : col.isWritable(),
//                           getIcon               : col.getIcon(),
//                           getManager            : col.getManager(),
//                           getDelegate           : col.getDelegate(),
//                           getChildren           : col.getChildren(),
//                           getKind               : col.getKind(),
//                           isCaseSensitive       : col.isCaseSensitive(),
//                           getProject            : col.getProject(),
//                           getDataSource         : col.getDataSource(),
//                           getVirtualFile        : col.getVirtualFile(),
//                           getMetaData           : col.getMetaData(),
//                           canNavigateToSource   : col.canNavigateToSource(),
//                           getDisplayOrder       : col.getDisplayOrder(),
//                           getDasParent          : col.getDasParent(),
//                           getLocationString     : col.getLocationString(),
//                           getDependences        : col.getDependences(),
//                           getBaseIcon           : col.getBaseIcon(),
//                           getNode               : col.getNode(),
//                           getTextLength         : col.getTextLength(),
//                           getFirstChild         : col.getFirstChild(),
//                           getLastChild          : col.getLastChild(),
//                           getNextSibling        : col.getNextSibling(),
//                           getTextOffset         : col.getTextOffset(),
//                           getPrevSibling        : col.getPrevSibling(),
//                           getPresentation       : col.getPresentation(),
//                           isPhysical            : col.isPhysical(),
//                           getTextRange          : col.getTextRange(),
//                           getPresentableText    : col.getPresentableText(),
//                           textToCharArray       : col.textToCharArray(),
//                           getStartOffsetInParent: col.getStartOffsetInParent(),
//                           getContext            : col.getContext(),
//                           getUseScope           : col.getUseScope(),
//                           getResolveScope       : col.getResolveScope(),
//                           getReferences         : col.getReferences(),
//                           getReference          : col.getReference(),
//                           getContainingFile     : col.getContainingFile(),
//                           getOriginalElement    : col.getOriginalElement(),
//                           getNavigationElement  : col.getNavigationElement(),
//                           getUserDataString     : col.getUserDataString(),
//                           isUserDataEmpty       : col.isUserDataEmpty(),
//                           getDbParent           : col.getDbParent(),
                   ]]

    }
}

def javaName(str, capitalize) {
    def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
            .join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_").replaceAll(/_/, "")
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}